/*
    import action专属store 继承import基类
*/
import $ from '@/common'
import Vue from 'vue'
var Store = {
  name: 'import_tempalte',
  state: {
    dataLoad: false,
    mappingLoad: false,
    isSetp: false,
    // 路径数据，定义位置待调整 0
    path: {
      save: '/service/{app}/excel/ds',
      detail: 'service/{app}/excel/ds/{id}',
      ds: '/service/{app}/pf/rdbs?enable_self=true',
      entity: '/service/{app}/pf/rdb/entities/{code}',
      struct: '/service/{app}/pf/rdb/entity/struct/{dsCode}/{entityCode}',
      upload: '/service/{app}/imp/ds/upload'
    },
    // 模板数据模型
    data: {
      name: null,
      code: null,
      sheet_name: null,
      type: null,
      repeat_rule: null,
      enable_create: false,
      ds_id: null,
      fields: []
    },
    sheetEntityCode: null,
    //建表的实体
    sheetEntity: [],
    // 实体数据
    entityData: [],
    // 实体结构数据
    structData: {},
    // 数据源数据
    dsData: [],
    // 文件表结构数据
    sheetData: {},
    // 映射数据
    mappingData: {},
    ds_code: null,
    fileName: null
  },
  getters: {
    dsCode(state) {
      for (let i in state.dsData) {
        if (state.dsData[i].id === state.data.ds_id) {
          return state.dsData[i].code
        }
      }
      return null
    }
  },
  actions: {
    fetchDs({
      commit,
      state
    }) {
      return $.link(state.path.ds).then((res) => {
        commit('setDsData', res.data)
      })
    },
    fetchEntity({
      commit,
      state,
      dispatch,
      getters
    }) {
      commit('setDsCode', getters.dsCode)
      return $.link(state.path.entity, null, {
        param: {
          code: getters.dsCode
        }
      }).then((res) => {
        commit('setEntityData', res.data)
      })
    },
    fetchStruct({
      commit,
      state,
      getters
    }, code) {
      if (state.structData[code]) {
        return new Promise((resolve) => {
          resolve(state.structData[code])
        })
      } else {
        return $.link(state.path.struct, null, {
          param: {
            dsCode: getters.dsCode,
            entityCode: code
          }
        }).then((res) => {
          commit('setStructData', {
            code,
            data: res.data
          })
        })
      }
    },
    findData({
      commit,
      state
    }, param) {
      return $.link(state.path.detail, null, {
        param
      }).then((res) => {
        commit('setData', res.data)
      })
    },
    submitData({
      state
    }) {
      var data = $.copyJson(state.data)
      // 暂时使用单处理流程
      data.process = [data.process]
    },
    createSheetData({
      state,
      commit
    }) {
      var sheetData = {}
      var sheetList = state.data.sheet_name.split(';')
      sheetList.forEach((name) => {
        sheetData[name] = []
      })
      state.data.fields.forEach((field) => {
        if (field.name !== null && sheetData[field.sheet_name] && sheetData[field.sheet_name].indexOf(field.name) < 0) {
          sheetData[field.sheet_name].push(field.name)
        }
      })
      commit('setSheetData', sheetData)
    },
    createMappingData({
      state,
      commit,
      dispatch
    }) {
      // code(TABLE_NAME)-index 映射
      var entityMap = {}
      state.entityData.forEach((entity, i) => {
        entityMap[entity.TABLE_NAME] = i
      })
      state.data.fields.forEach((field) => {
        var sheetMapping = state.mappingData[field.sheet_name]
        var entityIndex = entityMap[field.entity_code]
        if (entityIndex !== undefined) {
          if (!sheetMapping.entity[entityIndex]) {
            sheetMapping.entity[entityIndex] = []
          }
          sheetMapping.entity[entityIndex].push(field)
        }
      })
      var actionList = []
      for (let i in state.mappingData) {
        let mappingData = state.mappingData[i]
        for (let j in mappingData.entity) {
          if (!mappingData.entity[j]) {
            actionList.push(dispatch('fetchStruct', state.entityData[j].TABLE_NAME).then(() => {
              commit('createMappingItem', {
                iSheet: i,
                iEntity: j,
                update: true
              })
            }))
          }
          // 设置模式选中的实体
          if (mappingData.entity.showEntityIndex === null || mappingData.entity.showEntityIndex === undefined) {
            commit('updateMappingIndex', {
              sheet: i,
              index: j
            })
          }
        }
      }
      return Promise.all(actionList)
    },
    initMappingData({
      commit,
      state
    }) {
      var data = {}
      for (var i in state.sheetData) {
        data[i] = {
          // 当前展示的实体的序数
          showEntityIndex: null,
          // 记录不同的映射数据,见只为index
          entity: {}
        }
      }
      commit('setMappingData', data)
    },
    getSubmitData({
      state
    }) {
      state.data.sheet_name = $.listMap(state.sheetData).join(';') || state.data.sheet_name
      var submitData = $.copyJson(state.data)
      submitData.fields = [];
      for (let i in state.mappingData) {
        if (!state.data.enable_create) {
          for (let j in state.mappingData[i].entity) {
            //整理与转化
            state.mappingData[i].entity[j].forEach((field) => {
              var row = {
                ...field,
                store_field_code: `${field.entity_code}_${field.field_code}`,
                required: field.required ? 3 : 0,
                enable_trim: field.enable_trim ? 3 : 0
              }
              if (!field.convert) {
                field.convert_value = null
                field.convert_type = null
              }
              delete row.convert
              submitData.fields.push(row)
            })
          }
        } else {
          //整理与转化
          state.sheetEntity.forEach((field) => {
            var row = {
              ...field,
              store_field_code: `${field.entity_code}_${field.field_code}`,
              required: field.required ? 3 : 0,
              enable_trim: field.enable_trim ? 3 : 0
            }
            if (!field.convert) {
              field.convert_value = null
              field.convert_type = null
            }
            delete row.convert
            submitData.fields.push(row)
          })
        }
      }
      submitData.processes = []
      state.processes && state.processes.listData && state.processes.listData.forEach((item) => {
        if (item.entity_code) {
          submitData.processes.push({
            ...item,
            ds_id: submitData.ds_id
          })
        }
      })
      submitData.ds_code = state.ds_code

      return submitData
    }
  },
  mutations: {
    clear(state) {
      for (let i in Store.state) {
        if (typeof Store.state[i] === 'object') {
          Vue.set(state, i, $.copyJson(Store.state[i]))
        } else {
          state[i] = Store.state[i]
        }
      }
    },
    setData(state, data) {
      if (data.fields) {
        data.fields.forEach((field) => {
          $.setProp(field, {
            required: field.required === 3,
            enable_trim: field.enable_trim === 3,
            convert: (field.enable_trim > 0 || field.convert_type > 0)
          })
        })
      } else {
        data.fields = []
      }
      if (!data.ds_id) {
        data.ds_id = '-_self_-'
        data.ds_code = '-_self_-'
        state.ds_code = '-_self_-'
      }
      Vue.set(state, 'data', data)
    },
    updateData(state, {
      code,
      value
    }) {
      Vue.set(state.data, code, value)
    },
    setDsData(state, data) {
      Vue.set(state, 'dsData', data)
    },
    setDsCode(state, v) {
      state.ds_code = v
    },
    setEntityData(state, data) {
      Vue.set(state, 'entityData', data)
    },
    setSheetData(state, data) {
      Vue.set(state, 'sheetData', data)
    },
    setSheetEntityData(state, data) {
      var sheetData = {}
      var entityData = []
      state.sheetEntityCode = null
      //暂时只处理单表
      for (let i in data) {
        sheetData[i] = []
        data[i].forEach((field, index) => {
          sheetData[i].push(field.field_name)
          if (field.entity_code) {
            state.sheetEntityCode = field.entity_code
          }
          entityData.push({
            ...field,
            code: field.field_code,
            name: field.field_name,
            scope: field.scope || 'data',
            convert: (field.enable_trim > 0 || field.convert_type > 0),
            enable_trim: field.enable_trim || 0,
            convert_type: field.convert_type || null,
            convert_value: field.convert_value || null,
            required: field.required || 0
          })
        })
      }
      Vue.set(state, 'sheetEntity', entityData)
      Vue.set(state, 'sheetData', sheetData)
    },
    setMappingData(state, data) {
      Vue.set(state, 'mappingData', data)
    },
    setStructData(state, {
      data,
      code
    }) {
      Vue.set(state.structData, code, data)
    },
    setfileName(state, v) {
      state.fileName = v
    },
    headerNameChange(state, {
      table,
      index,
      e
    }) {
      if (state.sheetData[table]) {
        Vue.set(state.sheetData[table], index, e.target.value)
      }
    },
    // 表头位置向上调整
    headerSerialUp(state, {
      table,
      index
    }) {
      var sheet = state.sheetData[table]
      if (sheet && index > 0) {
        let temp = sheet[index - 1]
        Vue.set(sheet, index - 1, sheet[index])
        Vue.set(sheet, index, temp)
      }
    },
    headerSerialDown(state, {
      table,
      index
    }) {
      var sheet = state.sheetData[table]
      if (sheet && index < sheet.length) {
        let temp = sheet[index + 1]
        Vue.set(sheet, index + 1, sheet[index])
        Vue.set(sheet, index, temp)
      }
    },
    processEntityChange(state, {
      value,
      index
    }) {
      if (!state.data.processes[index]) {
        state.data.processes[index] = {}
      }
      $.setProp(state.data.processes[index], {
        entity_code: value,
        ds_id: state.data.ds_id,
        trans_ds: state.ds_code
      })
    },
    setMappingLoad(state, v) {
      state.mappingLoad = v
    },
    updateProcessData(state, {
      code,
      value,
      index
    }) {
      state.data.processes[index][code] = value
    },
    addProcessData(state) {
      state.data.processes.push({
        ds_id: state.data.ds_id,
        extract_expression: null,
        entity_code: null
      })
    },
    removeProcessData(state, index) {
      state.data.processes = state.data.processes.filter(function (v, i) {
        return index !== i
      })
    },
    setSetp(state, v) {
      state.isSetp = v
    },
    updateMappingIndex(state, {
      sheet,
      index
    }) {
      state.mappingData[sheet].showEntityIndex = index
    },
    createSheetEntityMapping(state) {
      var sheetToEntity = {}
      state.structData = {}
      state.data.fields.forEach((field) => {
        if (field.entity_code) {
          if (!state.structData[field.entity_code]) {
            state.structData[field.entity_code] = []
          }
          state.structData[field.entity_code].push(field)
          if (field.sheet_name && !sheetToEntity[field.sheet_name]) {
            sheetToEntity[field.sheet_name] = state.structData[field.entity_code]
          }
        }
        state.sheetEntity = state.structData[field.entity_code]
        state.sheetEntityCode = field.entity_code
      })
    },
    createMappingItem(state, {
      iEntity,
      iSheet,
      update
    }) {
      var entity
      var entityCode
      var mappingItem
      // 对于已经设置过的字段记录在map中，不进行重置
      var fieldMap = {}
      if (state.data.enable_create) {
        entity = state.sheetEntity
        entityCode = state.sheetEntityCode
        iEntity = 0
        state.structData[entityCode] = state.sheetEntity
        state.mappingData[iSheet].entity[iEntity] = []
      } else {
        entity = state.entityData[iEntity]
        entityCode = entity.TABLE_NAME
        if (state.mappingData[iSheet].entity[iEntity] && update) {
          mappingItem = state.mappingData[iSheet].entity[iEntity]
          state.mappingData[iSheet].entity[iEntity].forEach((field) => {
            fieldMap[field.field_code] = field
          })
        } else {
          mappingItem = state.mappingData[iSheet].entity[iEntity]
        }
      }
      if (state.structData[entityCode]) {
        let entityItem = mappingItem || []
        state.structData[entityCode].forEach((field) => {
          if (fieldMap[field.code]) {
            return
          }
          // 为每个实体字段设置
          let matchName = null
          for (let i in state.sheetData[iSheet]) {
            var headerName = state.sheetData[iSheet][i]
            if (headerName === field.name || field.name.indexOf(headerName) > -1) {
              matchName = headerName
              break
            }
          }
          entityItem.push({
            convert: false,
            name: matchName,
            sheet_name: iSheet,
            type: field.type, // 映射类型
            required: false, // 0x3v
            col_name: null,
            entity_code: entityCode,
            entity_name: entityCode,
            field_code: field.code || field.field_code,
            field_name: field.name || field.field_code,
            convert_type: null, // 1日期3状态5表达式
            convert_value: null,
            scope: 'data', // param;data;both
            enable_trim: false // 0x3v
          })
        })
        if (!mappingItem) {
          Vue.set(state.mappingData[iSheet].entity, iEntity, entityItem)
        }
      }
    }
  }
}
export default Store
